import urllib2
import sys
import socket
import urlparse
from xml.dom.minidom import parse, parseString



try:
    import terminal

    def prettyText(text,design):
        if isinstance(design,str):
            return terminal.AnsiText(text,[design])
        elif isinstance(design,list):
            return terminal.AnsiText(text,design)
        else:
            return text

except ImportError, e:

    def prettyText(text,design):
        return text


class bingSearch:

    def __init__(self, keyId):
        self.keyId = keyId


    def search(self, query):
        query = "Query=%27" + query + "%27&$format=atom"
        url = 'https://api.datamarket.azure.com/Bing/SearchWeb/v1/Web?' + query
        user = 'user'
        creds = ('%s:%s' % (user, self.keyId)).encode('base64')[:-1]
        auth = 'Basic %s' % creds
        user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; FDM; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 1.1.4322)'
        request = urllib2.Request(url)
        request.add_header('Authorization', auth)
        request.add_header('User-Agent', user_agent)
        requestor = urllib2.build_opener()
        result = requestor.open(request)
        data = result.read()
        requestor.close()
        return data


def searchIP(domain, keyId):

    ip = socket.gethostbyname(domain)
    sites = []

    bSearch = bingSearch(keyId)
    data = bSearch.search('ip%3a' + ip)

    xmldoc = parseString(data)
    nameEls = xmldoc.getElementsByTagName('d:DisplayUrl')
    for el in nameEls:
        temp = el.childNodes[0].nodeValue
        #print temp
        oUrl = urlparse.urlparse(temp)

        if oUrl.netloc not in sites and oUrl.netloc != '':
            sites.append(oUrl.netloc)

    return sites



if __name__ == '__main__':
    domain = sys.argv[1]
    key= '<keyId here, see windows Azure>'
    lstSite = searchIP(domain, key)
    if lstSite == []:
        print prettyText("[-] No Domains Found for: ",'red') + prettyText(domain,'blue')
    else:
        print prettyText("[+] Domains for: ", 'green') + prettyText(domain,'blue')
        for l in lstSite:
            print prettyText(" - ", 'cyan') + prettyText(l,'magenta')




